import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'package:amap_location/amap_location.dart';
import 'package:flutter/cupertino.dart';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';

import 'package:atten_sys/activities/day_off.dart';
import 'package:atten_sys/activities/self_info.dart';
import 'package:atten_sys/activities/work_status.dart';
import 'package:atten_sys/fregments/ActivityItems.dart';
import 'package:atten_sys/entity/Entity.dart';
import 'package:atten_sys/activities/login.dart';
import 'package:atten_sys/utils/utils.dart';
import 'package:atten_sys/activities/change_password.dart';
import 'package:atten_sys/utils/http.dart';

class Index extends StatefulWidget {
  final User user;

  Index({Key key, @required this.user});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _IndexState();
  }
}

class _IndexState extends State<Index> {
  String barcode;

  AMapLocation location;

  SharedPreferences preferences;

  HttpUtil _httpUtil = HttpUtil.getInstance();

  GlobalKey _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    // TODO: implement initState
    checkPermission();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '人事考勤APP',
      home: new Scaffold(
        key: _scaffoldKey,
          appBar: AppBar(
            actions: <Widget>[
              PopupMenuButton<String>(
                onSelected: (String v) {
                  //在退出前,要向网络发出退出请求，并清除缓存
                  logout();
                },
                itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                      new PopupMenuItem(value: 'exit', child: Text('退出登录'))
                    ],
              )
            ],
            brightness: Brightness.light,
            elevation: 0.3,
            title: new Text('人事考勤'),
            centerTitle: true,
          ),
          body: new Center(
              child: SizedBox(
            height: 100,
            width: 200,
            child: RaisedButton(
              color: Colors.blue,
              onPressed: scan,
              highlightColor: Colors.blue[700],
              colorBrightness: Brightness.dark,
              splashColor: Colors.grey,
              child: Text(
                '扫码考勤',
                style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),
              ),
            ),
          )),
          drawer: buildDrawer(widget.user)),
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
    );
  }

//  创建一个Drawer
  Widget buildDrawer(User user) {
    Widget userHeader = DrawerHeader(
        child: ListView(
      children: <Widget>[
        SizedBox(
          height: 40,
        ),
        Padding(
          padding: EdgeInsets.only(left: 20),
          child: Text(
            user.username,
            style: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
          ),
        ),
        SizedBox(
          height: 10,
        ),
        Padding(
          padding: EdgeInsets.only(left: 20),
          child: Text(
            user.jobNumber,
            style: TextStyle(fontSize: 16),
          ),
        )
      ],
    ));

    return new Drawer(
      elevation: 10,
      child: ListView(
        padding: EdgeInsets.all(0),
        children: <Widget>[
          userHeader,
          SizedBox(
            height: 10,
          ),
          labelBuilder(
              Icons.account_box,
              '我的资料',
              new ActivityItems(
                  title: '我的资料',
                  content: new SelfInfo(
                    user: widget.user,
                  ))),
          labelBuilder(Icons.work, '考勤情况',
              new ActivityItems(title: '考勤情况', content: new WorkStatus())),
          labelBuilder(Icons.add_box, '申请请假',
              new ActivityItems(title: '申请请假', content: new DayOff())),
          labelBuilder(Icons.add_to_home_screen, '修改密码',
              new ActivityItems(title: '修改密码', content: new ChangePass())),
        ],
      ),
    );
  }

  //创建一个标签
  Widget labelBuilder(IconData icon, String labelName, Widget toNew) {
    return ListTile(
      contentPadding: EdgeInsets.fromLTRB(30, 0, 0, 13),
      leading: new CircleAvatar(
        backgroundColor: Colors.grey[200],
        child: Icon(
          icon,
          size: 30,
          color: Colors.blueAccent,
        ),
      ),
      title: Padding(
          padding: EdgeInsets.only(left: 10),
          child: new Text(
            labelName,
            style: new TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
          )),
      onTap: () {
        Navigator.push(
          context,
          PageRouteBuilder(
              pageBuilder: (BuildContext context, Animation a1, Animation a2) {
            return toNew;
          }, transitionsBuilder:
                  (BuildContext c, Animation a1, Animation a2, Widget w) {
            return SwitchAnimate.createTransition(a1, w);
          }),
        );
      },
    );
  }

  //创建一个扫描二维码的方法
  scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      if (barcode.substring(0, 42) !=
          'http://47.100.219.132:8080/attendance/app/') {
        DialogUtil.createDialog(context, '错误', '错误的二维码');
        return;
      }
      AMapLocation location = await getLocation();
      DialogUtil.createLoading(context, '请稍等', submitInfo(barcode, location),
          (data) {
        if (data['payload'] != null) {
          DialogUtil.createDialog(context, '提示', data['payload']);
        } else
          DialogUtil.createDialog(context, '提示', data['msg']);
      });
    } on FormatException {
      setState(() {
        this.barcode = null;
      });
    } catch (e) {
      print('$e');
    }
  }

  //创建定位的方法
  Future<AMapLocation> getLocation() async {
    //先启动定位工具
    await AMapLocationClient.startup(new AMapLocationOption(
        desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyBest));
    //获取定位
    AMapLocation location = await AMapLocationClient.getLocation(true);
    if (location.code == 12) {
      DialogUtil.createDialog(context, '提示', '请打开GPS定位按钮');
    }
    return location;
  }

  //查看对应的权限
  checkPermission() async {
    //获取数据储存对象
    preferences = await SharedPreferences.getInstance();

    print('checkPermission');

    bool hasLPermission =
        await SimplePermissions.checkPermission(Permission.WhenInUseLocation);
    bool hasCPermission =
        await SimplePermissions.checkPermission(Permission.Camera);
    if (!hasLPermission) {
      PermissionStatus status = await SimplePermissions.requestPermission(
          Permission.WhenInUseLocation);
      if (status != PermissionStatus.authorized) {
        DialogUtil.createDialog(context, '提示', '定位权限获取失败');
      }
    }
    if (!hasCPermission) {
      PermissionStatus status =
          await SimplePermissions.requestPermission(Permission.Camera);
      if (status != PermissionStatus.authorized) {
        DialogUtil.createDialog(context, '提示', '照相机权限获取失败');
      }
    }
  }

  //发送网络请求
  Future<dynamic> submitInfo(String url, AMapLocation location) async {
    dynamic data = await _httpUtil.post('$url',
        data: {'latitude': location.latitude, 'longitude': location.longitude},
        options: new Options(
            headers: {'Authorization': preferences.getString('Authorization')},
            contentType:
                ContentType.parse("application/x-www-form-urlencoded")));
    return data;
  }

  //创建一个退出登录的网络请求
  logout() async {
    dynamic data = await _httpUtil.get('/app/logout', options: new Options(
      headers: {'Authorization': preferences.getString('Authorization')}
    ), scaffoldKey: _scaffoldKey);
    print(preferences.getString('Authorization'));
    if (data['payload'] != null) {
      preferences.remove('UID');
      preferences.remove('Authorization');
      Navigator.pushAndRemoveUntil(context,
          MaterialPageRoute(builder: (BuildContext context) {
        return LoginWidget();
      }), (r) => r == null);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //在生命周期结束后关闭
    AMapLocationClient.shutdown();
    super.dispose();
  }
}
